import { getUserAddressList, getUserInfo, setUserInfo, getUserCertify, setUserCertify } from '../../services/user';
import { confirmOrder, submitOrder, payOrder } from '../../services/order';
import parser from 'rich-text-parser'
var app = getApp()
Page({
  data: {
    showBottom: false,
    canIUseAuthButton: true,
    checked: false,
    pushdata: {},
    addressList: [],
    orderPrice: 0,
    chooseAddressInfo: {},
    orderInfo: {},
    userCouponId: 0,
    selectCoupon: {},
    userInfo: {},
    chooseAddressId: 0,
    showcoupontitle: '',
    showBottom2: false
  },
  onPopupClose() {
    this.setData({
      showBottom: false
    });
  },
  onPopupClose2() {
    this.setData({
      showBottom2: false
    });
  },
  onPopupOpen() {
    this.setData({
      showBottom: true,
    });

  },
  onPopupOpen2() {
    this.setData({
      showBottom2: true,
    });
    if (!this.data.nodes) {
      if (getApp().globalData.playforminfo.lossRule) {
        //  parser.definedCustomTag({ figure: 'div', figcaption: '' })
        //const nodes = parser.getRichTextJson(getApp().globalData.playforminfo.lossRule)
        const nodes = getApp().globalData.playforminfo.lossRule
        this.setData({
          nodes: nodes
        });
      }
    }

  },

  getUserCertify() {
    if (this.data.userInfo.isReal == 2) {
      this.addOrder()
    } else {
      var that = this
      getUserCertify({}).then(res => {
        if (res.code == "000000") {
          my.startAPVerify({
            url: res.data.certifyUrl,
            certifyId: res.data.certifyId,
            success: function (res2) {
              setUserCertify({ certifyResult: 1 }).then(res3 => {
                if (res3.code == "000000") {
                  that.addOrder()
                }
              })
            },
            fail: function (res2) {
              setUserCertify({ certifyResult: 0 }).then(res3 => {

              })
            },
            complete: function (res2) {
              console.log('complete', res2)
            }
          })

        }
      })
    }
  },

  getUserInfo() {
    getUserInfo({}).then((res) => {
      if (res.code == "000000") {
        this.setData({ userInfo: res.data })
      }
    })
  },
  onShow() {
    my.setNavigationBar({
      title: '确认订单',
      backgroundColor: '#4BA3F9'
    })
    this.setData({ chooseAddressId: app.globalData.chooseAddressID })
    this.confirmOrder()
    this.getUserAddressList()
    this.getUserInfo()
  },
  onLoad(event) {
    this.setData({ pushdata: event })
  },
  verifyOrder() {
    if (Object.keys(this.data.chooseAddressInfo).length <= 0) {
      my.showToast({
        type: 'fail',
        content: '请选择地址',
        duration: 2000,
      });
      return
    }
    if (!this.data.checked) {
      my.showToast({
        type: 'fail',
        content: '请阅读材料',
        duration: 2000,
      });
      return
    }
  },
  addOrder() {

    let param = {
      rentDay: this.data.pushdata.rentDay,
      rentTime: this.data.pushdata.rentTime,
      skuId: this.data.pushdata.skuId,
      userAddressId: this.data.chooseAddressInfo.id
    }
    if (this.data.userCouponId > 0) {
      param.userCouponId = this.data.userCouponId
    }
    submitOrder(param).then((res) => {

      if (res.code == "000000") {
        let orderID = res.data
        payOrder({ orderId: res.data }).then(res2 => {
          if (res2.code == "000000") {
            if (res2.data.payType == 0) {
              my.showToast({
                type: 'fail',
                content: res2.data.payData,
                duration: 2000,
              });
              return
            } else if (res2.data.payType == 1) {
              my.tradePay({
                tradeNO: res2.data.payData,
                success: function (res3) {
                  console.log(res3)
                  // let resultAli = JSON.stringify(res3)
                  let resultAli = res3
                  if (resultAli.resultCode == "9000") {
                    my.navigateTo({
                      url: "/pages/result/success/success?orderid=" + orderID
                    })
                  } else {
                    my.showToast({
                      type: 'fail',
                      content: resultAli.memo,
                      duration: 2000,
                    });
                  }

                },
                fail: function (res) {
                  console.log(res)
                  // my.alert({
                  //   content: JSON.stringify(res),
                  // });
                },
              });
            }
            else if (res2.data.payType == 2) {
              my.tradePay({
                // 调用资金冻结接口（alipay.fund.auth.order.app.freeze），获取资金授权参数
                orderStr: res2.data.payData,
                success: (res3) => {

                  console.log(res3)
                  // let resultAli = JSON.stringify(res3)
                  let resultAli = res3
                  if (resultAli.resultCode == "9000") {
                    my.navigateTo({
                      url: "/pages/result/success/success?orderid=" + orderID
                    })
                  } else {
                    my.showToast({
                      type: 'fail',
                      content: resultAli.memo,
                      duration: 2000,
                    });
                  }
                },
                fail: (res) => {
                  console.log(res)
                  // my.alert({
                  //   content: JSON.stringify(res),
                  // });
                }
              });
            }

          }
        })
      }
    })
  },
  onCheckReal() {
    if (this.data.userInfo.isReal <= 0) {
      my.navigateTo({
        url: "/pages/realName/realName"
      })
      return false
    } else {
      return true
    }
  },
  onGetAuthorize(res) {
    if (Object.keys(this.data.chooseAddressInfo).length <= 0) {
      my.showToast({
        type: 'fail',
        content: '请选择地址',
        duration: 2000,
      });
      return
    }
    if (!this.data.checked) {
      my.showToast({
        type: 'fail',
        content: '请阅读材料',
        duration: 2000,
      });
      return
    }
    if (!this.onCheckReal()) {
      return
    }
    if (this.data.userInfo.userPhone == undefined || this.data.userInfo.userPhone.length <= 0) {
      my.getPhoneNumber({
        success: (res) => {
          let encryptedData = JSON.parse(res.response).response;
          setUserInfo({
            userPhone: encryptedData
          }).then((res) => {
            if (res.code == "000000") {
              // this.onCheckReal()
              this.getUserCertify()
            }
          })
        },
        fail: (res) => {
          console.log(res);
          my.showToast({
            type: 'fail',
            content: '授权失败',
            duration: 2000,
          });
        },
      });
    } else {
      // this.onCheckReal()
      this.getUserCertify()
    }
  },
  async confirmOrder() {
    let param = {
      rentDay: this.data.pushdata.rentDay,
      rentTime: this.data.pushdata.rentTime,
      skuId: this.data.pushdata.skuId
    }
    await confirmOrder(param).then((res) => {
      console.log(res)
      if (res.code == "000000") {
        this.setData({
          orderInfo: res.data
        });
        this.setData({ orderPrice: res.data.rentStageAmount })
        if (res.data.couponVOList != undefined) {
          this.setData({ showcoupontitle: '共' + res.data.couponVOList.length + '张优惠券' })
        }
      }
    })
  },
  addressAddClick() {
    my.navigateTo({
      url: '/pages/addAddress/addAddress',
    })
  },
  addressClick() {
    my.navigateTo({
      url: '/pages/shipping/shipping?type=1&data=' + JSON.stringify(this.data.pushdata)
    })
  },
  onChange(e) {
    this.setData({ checked: e.detail.value })
  },
  getUserAddressList() {
    getUserAddressList({}).then((res) => {
      if (res.code == "000000") {
        this.setData({
          addressList: res.data
        });
        if (this.data.chooseAddressId > 0) {
          res.data.forEach(element => {
            if (element.id == this.data.chooseAddressId) {
              this.setData({
                chooseAddressInfo: element
              });
            }
          });
        } else {
          if (res.data.length > 0) {
            app.globalData.chooseAddressID = res.data[0].id
            console.log(app.globalData.chooseAddressID)
            this.setData({
              chooseAddressInfo: res.data[0]
            });
          }
        }
      }
    })
  },
  selectcoupon(event) {
    console.log(event)
    this.data.orderInfo.couponVOList.forEach(element => {
      if (element.userCouponId == event.target.dataset.id) {
        this.setData({
          showcoupontitle: '－¥' + element.couponAmount,
          userCouponId: event.target.dataset.id,
          selectCoupon: element
        });
      }
    });
    this.setData({ orderPrice: parseFloat(this.data.orderInfo.rentStageAmount - this.data.selectCoupon.couponAmount).toFixed(2) })
    this.onPopupClose()

  },
  clearcoupon() {
    this.setData({
      userCouponId: 0,
      selectCoupon: {}
    });
    this.setData({ showcoupontitle: '共' + this.data.orderInfo.couponVOList.length + '张优惠券' })
    this.setData({ orderPrice: this.data.orderInfo.rentStageAmount })
    this.onPopupClose()
  },
});
